package com.lemon.smartsafetynew.ui.fragment.base;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.app.RefreshType;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.HttpEventListener;
import com.lemon.smartsafety.listener.PullLoadMoreListener;
import com.lemon.smartsafety.listener.PullRefreshListener;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.view.list.MultiStateView;
import com.lemon.smartsafetynew.ui.adapter.common.StringAdapter;
import com.lemon.smartsafetynew.util.common.CommonUtil;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import kale.adapter.LemonRcvAdapter;

/**
 * Created by Andrew on 2017/7/26.
 */

public abstract class BaseTopBtnPullToRefreshFragment<L, H extends List> extends BaseFragment implements HttpEventListener<H>, PullRefreshListener, PullLoadMoreListener {

    private LoggerHelper loggerHelper = new LoggerHelper(BaseTopBtnPullToRefreshFragment.class);

    // ======== secondaryLayout ========

    @Bind(R.id.one_label_tv)
    public TextView oneLabelTv;

    @Bind(R.id.one_content_tv)
    public TextView oneContentTv;

    @Bind(R.id.one_layout)
    public LinearLayout oneLayout;

    @Bind(R.id.two_label_tv)
    public TextView twoLabelTv;

    @Bind(R.id.two_content_tv)
    public TextView twoContentTv;

    @Bind(R.id.two_layout)
    public LinearLayout twoLayout;

    @Bind(R.id.three_label_tv)
    public TextView threeLabelTv;

    @Bind(R.id.three_content_tv)
    public TextView threeContentTv;

    @Bind(R.id.three_layout)
    public LinearLayout threeLayout;

    @Bind(R.id.four_label_tv)
    public TextView fourLabelTv;

    @Bind(R.id.four_content_tv)
    public TextView fourContentTv;

    @Bind(R.id.four_layout)
    public LinearLayout fourLayout;

    @Bind(R.id.secondary_layout)
    public LinearLayout secondaryLayout;

    // ======== spinnerLayout ========
    @Bind(R.id.date_tv)
    public TextView dateTv;

    @Bind(R.id.spinner_text)
    public TextView spinnerText;

    @Bind(R.id.spinner_choose_layout)
    public LinearLayout spinnerChooseLayout;

    @Bind(R.id.spinner_layout)
    public RelativeLayout spinnerLayout;

    @Bind(R.id.image)
    public ImageView image;

    // ======== listBarLayout ========
    @Bind(R.id.list_bar_layout)
    public LinearLayout listBarLayout;

    // ======== btnLayout ========
    @Bind(R.id.btn_layout)
    public LinearLayout btnLayout;

    @Bind(R.id.pullToRefreshRecyclerView)
    public PullToRefreshRecyclerView mPullToRefreshRecyclerView;

    @Nullable
    @Bind(R.id.multiStateView)
    public MultiStateView mMultiStateView;


    @Nullable
    @Bind(R.id.float_button)
    protected FloatingActionButton fab;

    protected int currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;

    protected int pageSize = Constants.PAGE_SIZE;

    public H mDataList = (H) new ArrayList<>();

    protected LemonRcvAdapter<L> mAdapter;

    @Override
    protected void initViews() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(IApplication.context(), LinearLayoutManager.VERTICAL, false);
        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        mPullToRefreshRecyclerView.setLayoutManager(layoutManager);
        mAdapter = getLemonAdapter();
        mPullToRefreshRecyclerView.setAdapter(mAdapter);
        mPullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;
                onPullRefresh();
            }
        });
        mPullToRefreshRecyclerView.setOnPullDownToRefreshListener(new PullToRefreshRecyclerView.OnPullDownToRefreshListener() {
            @Override
            public void onRefresh() {
                onLoadMore();
            }
        });

        mMultiStateView.setErrorRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                mPullToRefreshRecyclerView.beginRefreshing();
            }
        });
    }

    public void doPullRefresh() {
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        mPullToRefreshRecyclerView.beginRefreshing();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (goRefreshOnCreate()) {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            mPullToRefreshRecyclerView.beginRefreshing();
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_refresh_top_btn;
    }

    @Override
    protected void getBaseArguments() {

    }

    /**
     * 是否在视图创建好后，就自动下来刷新
     *
     * @return
     */
    public abstract boolean goRefreshOnCreate();


    /**
     * 设置页面的Adapter
     *
     * @return
     */
    public abstract LemonRcvAdapter<L> getLemonAdapter();

    /**
     * 给请求设置一个Tag 可以过滤OnEvent的处理
     *
     * @return
     */
    public abstract String getHttpTag();


    /**
     * 数据请求事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent<H> event) {
        if (!getHttpTag().equals(event.getTag())) {
            return;
        }
        if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
        } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow() && mPullToRefreshRecyclerView != null) {
            RefreshType type = (RefreshType) event.getOther();
            if (RefreshType.REFRESH == type) {
                mPullToRefreshRecyclerView.onRefreshComplete();
            } else {
                mPullToRefreshRecyclerView.setFooterComplete();
            }
            if (Constants.Result.SUCCESS == event.getEventResult()) {
                if (RefreshType.REFRESH == type) {
                    httpRefresh(event.getObj());
                } else {
                    httpLoadMore(event.getObj());
                }
                currentPage++;
            } else if (Constants.Result.ERROR == event.getEventResult()) {
                if (RefreshType.REFRESH == type) {
                    httpRefreshError(event.getMsg());
                } else {
                    httpLoadMoreError(event.getMsg());
                }
            }

            //            mPullToRefreshRecyclerView.setFooterRetryListener(new View.OnClickListener() {
            //                @Override
            //                public void onClick(View v) {
            //                    loggerHelper.w("retry");
            //                }
            //            });
        }
    }


    @Override
    public void httpRefresh(H data) {
        if (data != null && !data.isEmpty()) {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            if (data.size() < pageSize) {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                //mPullToRefreshRecyclerView.setFooterComplete();
            } else {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.BOTH);
            }
            mDataList.clear();
            mAdapter.notifyDataSetChanged();
            mAdapter.addItems(data);
        } else {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        }
    }

    @Override
    public void httpLoadMore(H data) {
        if (data != null && !data.isEmpty()) {
            if (data.size() < pageSize) {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                mPullToRefreshRecyclerView.setFooterComplete();
            } else {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.BOTH);
            }
            mAdapter.addItems(data);
        }
    }

    @Override
    public void httpRefreshError(String msg) {
        mHUDUtil.showErrorTip(msg);
        mMultiStateView.setErrorTip(msg);
    }

    @Override
    public void httpLoadMoreError(String msg) {
        //mHUDUtil.showErrorTip(msg);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    private PopupWindow popupWindow;

    /**
     * PopWindow方法
     * @param view
     */
    public void showPopupWindow(View view, RecyclerTClickListener<String> listener, List<String> list) {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(getmContext()).inflate(
                R.layout.popup_recycler_layout, null);
        // 设置按钮的点击事件
        RecyclerView recyclerView = (RecyclerView) contentView.findViewById(R.id.recyclerView);

        popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 设置好参数之后再show
        popupWindow.showAsDropDown(view, -1 * CommonUtil.convertDipOrPx(getmContext(), 0), 5);

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getmContext(), LinearLayoutManager.VERTICAL, false);
        LemonRcvAdapter<String> popUpAdapter = new StringAdapter(list, listener);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(popUpAdapter);
        popUpAdapter.notifyDataSetChanged();

    }

    /**
     * PopWindow dismiss
     */
    public void dismissPopWindow() {
        popupWindow.dismiss();
    }
}
